import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia' //pinia
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' //pinia的持久化插件
// import pinia from './stores'


import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// @ts-expect-error Element Plus 的类型定义文件有问题
import zhCn from 'element-plus/dist/locale/zh-cn.mjs' //引入国际化配置, 选择中文
import * as ElementPlusIconsVue from '@element-plus/icons-vue' //引入icon

// 调试环境变量
console.log('🔧 环境变量检查:')
console.log('VITE_USE_MOCK:', import.meta.env.VITE_USE_MOCK)
console.log('VITE_API_BASE_URL:', import.meta.env.VITE_API_BASE_URL)
console.log('NODE_ENV:', import.meta.env.NODE_ENV)

// 全局错误处理
window.addEventListener('unhandledrejection', (event) => {
  console.error('未处理的Promise拒绝:', event.reason)
  event.preventDefault()
})

window.addEventListener('error', (event) => {
  console.error('全局错误:', event.error)
})

// 检查是否启用Mock
const shouldUseMock = import.meta.env.VITE_USE_MOCK === 'true'

if (shouldUseMock) {
  console.log('✅ Mock 模式已启用，正在加载 Mock...')
  // 使用动态导入替代 require
  import('mockjs').then((Mock) => {
    // 配置Mock，让它可以拦截带有/api前缀的请求
    Mock.default.setup({
      timeout: '200-600'
    });

    // 导入mock文件
    return Promise.all([
      import('./mock/loginMock'),
      import('./mock/accountInfoMock'),
      import('./mock/accountPermissionManagementMock'),
      import('./mock/logMock'),
      // import("./mock/statisticsMock"),
    ]);
  }).then(() => {
    console.log('✅ Mock 加载完成')
  }).catch((error) => {
    console.error('❌ Mock 加载失败:', error)
  })
} else {
  console.log('❌ Mock 模式未启用，将使用真实 API')
}

const app = createApp(App)

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

app.use(pinia)
app.use(router)
app.use(ElementPlus, {
  locale: zhCn,
})

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.mount('#app')

